package com.jjty.dataGenerator.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {


    public static final String SALT = "xykj-2023bg@";


    /**
     * 生成token
     * @param map
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String createToken(Map<String,String> map) throws UnsupportedEncodingException {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,7);
        Map<String,Object> header = new HashMap<>();
        JWTCreator.Builder builder = JWT.create();
        builder.withHeader(header);

        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        String token = builder
                //过期时间
                //.withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SALT));
        return token;
    }


    /**
     * 验证token
     */
    public static void verify(String token) throws UnsupportedEncodingException {
        JWT.require(Algorithm.HMAC256(SALT)).build().verify(token);
    }

    /**
     * 获取Claim中的键值对数据
     * @return
     */
    public static Map<String,String> getTokenInfo(String token)  {
        try{
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SALT)).build().verify(token);
            Map<String,String> map = new HashMap<>();
            verify.getClaims().forEach((k,v)->{
                map.put(k,v.asString());
            });
            return map;
        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


}
